package org.yxj.requestlibaray.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.yxj.requestlib.i.CurrentUploadFileListener;
import org.yxj.requestlib.i.UploadFileCallback;
import org.yxj.requestlib.manager.uploadfile.FileUploadRequestManager;
import org.yxj.requestlib.manager.uploadfile.UpLoadFileQueueManager;
import org.yxj.requestlibaray.R;
import org.yxj.requestlibaray.bean.FileBean;
import org.yxj.requestlibaray.bean.MultipartBodyBean;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;

import okhttp3.MultipartBody;

public class UpLoadFileListActivity extends AppCompatActivity {


    private String rootFilePath = Environment.getExternalStorageDirectory().getPath()+ File.separator+"XJ_TakePhoto";
    private RecyclerView mRecyclerView ;
    private FileAdapter adapter;
    private List<FileBean> list = new ArrayList<>() ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_up_load_file_list);
        initView();
        initData();
    }


    private void initData() {
        File file = new File(rootFilePath);
        if (file.exists() && !file.isFile()){
            File[] l = file.listFiles();
            for (File f:l){
                list.add(new FileBean(f.getName(),f.getAbsolutePath())) ;
            }
            adapter.notifyDataSetChanged();
        }
    }



    private void initView() {
        mRecyclerView = findViewById(R.id.mRecyclerView);
        LinearLayoutManager linearLayoutManager= new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,RecyclerView.VERTICAL);
        mRecyclerView.addItemDecoration(dividerItemDecoration);
        mRecyclerView.setAdapter(adapter = new FileAdapter(list));

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                FileBean item = list.get(position);
                item.time = System.currentTimeMillis();
                UpLoadFileQueueManager.getInstance().add(item);
            }
        });

        UpLoadFileQueueManager.getInstance().addCurrentUploadFileListener(new MyCurrentUploadFileListener());
    }



    public class  MyCurrentUploadFileListener implements CurrentUploadFileListener<FileBean> {

        @Override
        public void onPing(PriorityBlockingQueue<FileBean> queue) {
            Iterator<FileBean> it = queue.iterator();
            while (it.hasNext()){
                FileBean item = it.next();
                Button btn_upload =  item.helper.getView(R.id.btn_upload);
                btn_upload.setText("等待上传");
                btn_upload.setEnabled(false);
            }
        }

        @Override
        public void onUpload(FileBean o) {
            Log.v("====onUpload===","onUpload = "+o.toString());
            postFileTask(o);
        }
    }


    private class FileAdapter extends BaseQuickAdapter<FileBean, BaseViewHolder>{

        public FileAdapter( @Nullable List<FileBean> data) {
            super(R.layout.item_file_layout, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, FileBean item) {
            helper.setIsRecyclable(false);
            item.helper = helper ;

            ImageView imageView = helper.getView(R.id.img);
            Glide.with(UpLoadFileListActivity.this).load(item.filePath).into(imageView);
            helper.setText(R.id.name,item.fileName);
            ProgressBar mProgressBar = helper.getView(R.id.mProgressBar);
            mProgressBar.setProgress(item.progress);

            Button btn_upload =  item.helper.getView(R.id.btn_upload);
            if (item.isSuccess){
                btn_upload.setText("上传完成");
                btn_upload.setEnabled(false);
            }else {
                btn_upload.setText("上传");
                btn_upload.setEnabled(true);
            }
            helper.addOnClickListener(R.id.btn_upload);
        }
    }


    /**
     * 使用 okHttp 实现图片上传
     *
     * @param realFilePath
     */
    private void postFileTask(final FileBean item) {
        MultipartBody.Builder body =  new MultipartBodyBean(item.filePath).build();
        FileUploadRequestManager.getInstance().uploadFileByOkHttp(
                "http://inte.zbs6.com/inte/interface.ashx/",
                body, new UploadFileCallback<String>() {
                    @Override
                    public void progress(long total, long current) {
                        final float radio = (float) (current* 1.0 / total);
                        Log.v("[ApiRequest]","onNext - > progress   = "+ radio * 100);
                        item.progress=((int) (radio * 100));
                        item.currentFinishProgress = ((int)(radio * 100)+"/%");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Button btn_upload =  item.helper.getView(R.id.btn_upload);
                                btn_upload.setText(item.currentFinishProgress);
                                btn_upload.setEnabled(false);
                                ProgressBar mProgressBar =  item.helper.getView(R.id.mProgressBar);
                                mProgressBar.setProgress(item.progress);
                            }
                        });
                    }
                    @Override
                    public void success(String o) {
                        UpLoadFileQueueManager.getInstance().remove(item);
                        item.isSuccess = true ;
                        item.progress = 100;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ProgressBar mProgressBar =  item.helper.getView(R.id.mProgressBar);
                                mProgressBar.setProgress(item.progress);

                                Button btn_upload =  item.helper.getView(R.id.btn_upload);
                                btn_upload.setText("上传完成");
                                btn_upload.setEnabled(false);
                            }
                        });
                        Log.v("[ApiRequest]","onNext - > success = "+o);
                    }

                    @Override
                    public void failed(int code, String error) {
                        UpLoadFileQueueManager.getInstance().remove(item);
                        item.isSuccess = false ;
                        Log.v("[ApiRequest]","onNext - > error = "+error);
                    }
                });
    }
}